package controller.business.managerAssess;

import base.response.OffsetLimitPage;
import controller.common.BaseController;
import controller.common.StaticConstant;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import response.CommonResult;
import services.business.BusinessInfoServices;
import services.business.ManagerAssessServices;
import services.dictionary.ManagerAssessTypeServices;
import util.DateUtil;
import util.io.UploadDownloadFileUtil;
import util.key.IDFactory;
import wt.entity.business.*;
import wt.entity.dictionary.ManagerAssessType;
import wt.staticData.ShortData;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.*;

/**
 * 功能:
 * 作者: 洪世成
 * 日期: 2017/9/9
 * 版权所有: admin
 */
@Controller
@RequestMapping("business/managerAssess")
public class ManagerAssessController extends BaseController {
    @Autowired
    ManagerAssessServices managerAssessServices;
    @Autowired
    ManagerAssessTypeServices managerAssessTypeServices;
    @Autowired
    BusinessInfoServices businessInfoServices;


    @RequiresPermissions("business:managerAssess:default")
    @RequestMapping("index")
    public String index(Short managerIsAssess,Map map) {
        map.put("managerIsAssess",managerIsAssess);
        return "business/managerAssess/index";
    }


    @RequiresPermissions("business:managerAssess:default")
    @RequestMapping("editDlg")
    public String editDlg(@RequestParam(value = "businessId") String businessId, Map map) throws Exception {

        BusinessInfo businessInfo = businessInfoServices.selectByPrimaryKey(businessId);
        if (businessInfo.getManagerIsAssess() == 1) {
            map.put(StaticConstant.ERROR_MESSAGE, "已评价");
            return StaticConstant.ERROR_DLG;
        }

        if (!businessInfo.getManagerId().equals(getLoginAccount().getStaffInfo().getId())) {
            map.put(StaticConstant.ERROR_MESSAGE, "改业务您不能评价！");
            return StaticConstant.ERROR_DLG;
        }

        List<ManagerAssessType> managerAssessTypeList = managerAssessTypeServices.selectManagerAssessType(businessInfo.getItemId(), true);

        map.put("managerAssessTypeList", managerAssessTypeList2Map(managerAssessTypeList));
        map.put("businessInfo", businessInfo);
        map.put(StaticConstant.EDIT_URL, "business/managerAssess/insert");
        map.put(StaticConstant.EDIT_OPERATE_TYPE, StaticConstant.EDIT_INSERT);

        return "business/managerAssess/editDlg";
    }

    public  Map<ManagerAssessType, List<ManagerAssessType>> managerAssessTypeList2Map(List<ManagerAssessType> list) {
        Map<ManagerAssessType, List<ManagerAssessType>> managerAssessListMap = new LinkedHashMap<ManagerAssessType, List<ManagerAssessType>>();
        String rootId = null;
        for (ManagerAssessType managerAssessType : list) {
            if (managerAssessType.getPid() == null) {
                rootId = managerAssessType.getId();
                break;
            }
        }

        for (ManagerAssessType managerAssessType1 : list) {
            if (rootId.equals(managerAssessType1.getPid())) {
                List<ManagerAssessType> temp = new ArrayList<ManagerAssessType>();
                for (ManagerAssessType managerAssessType2 : list) {
                    if (managerAssessType1.getId().equals(managerAssessType2.getPid())) {
                        temp.add(managerAssessType2);
                    }
                }
                managerAssessListMap.put(managerAssessType1, temp);
            }
        }
        return managerAssessListMap;
    }



    @RequiresPermissions("business:managerAssess:default")
    @ResponseBody
    @RequestMapping("insert")
    public CommonResult insert(ManagerAssessList managerAssessList, String businessId) throws Exception {
        CommonResult commonResult = CommonResult.newCommonResult();
        BusinessInfo businessInfo = businessInfoServices.selectByPrimaryKey(businessId);
        if (businessInfo.getManagerIsAssess() == 1) {
            commonResult.setMessage("已评价");
            return commonResult;
        }

        List<ManagerAssessType> managerAssessTypeList = managerAssessTypeServices.selectManagerAssessType(businessInfo.getItemId(), true);
        List<ManagerAssess> managerAssessAll = new ArrayList<ManagerAssess>();
        boolean flag;
        for (ManagerAssessType managerAssessType : managerAssessTypeList) {
            if (managerAssessType.getCurrentDepth().equals(managerAssessType.getMaxDepth())) {//叶子节点时进入
                flag = false;
                for (ManagerAssess managerAssess : managerAssessList.getManagerAssessList()) {
                    if (managerAssess.getAccessTypeId().equals(managerAssessType.getId())) {
                        if (!"-".equals(managerAssess.getResult()) && !"Y".equals(managerAssess.getResult()) && !"N".equals(managerAssess.getResult())) {
                            commonResult.setMessage(managerAssessType.getName() + " 评价异常!!");
                            return commonResult;
                        } else {
                            flag = true;
                            managerAssess.setAccessTypeName(managerAssessType.getName());
                            managerAssess.setAccessTypePid(managerAssessType.getPid());
                            managerAssess.setAccessTypeNum(managerAssessType.getNum());
                            managerAssess.setBusinessId(businessId);
                            managerAssessAll.add(managerAssess);
                        }
                    }
                }
                if (!flag) {
                    commonResult.setMessage(managerAssessType.getName() + " 未评价!!");
                    return commonResult;
                }
            } else {
                ManagerAssess managerAssess = new ManagerAssess();
                managerAssess.setResult("*");
                managerAssess.setAccessTypeId(managerAssessType.getId());
                managerAssess.setAccessTypeName(managerAssessType.getName());
                managerAssess.setAccessTypePid(managerAssessType.getPid());
                managerAssess.setAccessTypeNum(managerAssessType.getNum());
                managerAssess.setBusinessId(businessId);
                managerAssessAll.add(managerAssess);
            }
        }


        managerAssessServices.insertSelective(managerAssessAll, businessId);
        return commonResult.setSuccess();
    }


    @RequiresPermissions("business:managerAssess:default")
    @ResponseBody
    @RequestMapping("select")
    public OffsetLimitPage select(
            String companyName,
            String productName,
            @DateTimeFormat(pattern = "yyyy-MM-dd") Date startTime,
            @DateTimeFormat(pattern = "yyyy-MM-dd") Date endTime,
            Short managerIsAssess,
            Integer offset,
            Integer limit
    ) throws Exception {

        BusinessInfoExample businessInfoExample = new BusinessInfoExample();
        BusinessInfoExample.Criteria criteria = businessInfoExample.createCriteria();
        businessInfoExample.setOrderByClause("ID DESC");
        criteria.andManagerIdEqualTo(getLoginAccount().getStaffInfo().getId()).andBusinessWorkFlowEqualTo(ShortData.s3);

        if (!StringUtils.isBlank(companyName)) {
            criteria.andCompanyNameLike("%" + companyName + "%");
        }

        if (!StringUtils.isBlank(productName)) {
            criteria.andProductNameLike("%" + productName + "%");
        }

        if (startTime != null) {
            criteria.andEndTimeGreaterThanOrEqualTo(startTime);
        }

        if (endTime != null) {
            criteria.andEndTimeLessThan(DateUtil.moveDate(endTime, 1));
        }

        if (managerIsAssess != null) {
            criteria.andManagerIsAssessEqualTo(managerIsAssess);

        }
        return businessInfoServices.selectByExample(businessInfoExample, offset, limit);
    }


    @RequiresPermissions("business:managerAssess:default")
    @ResponseBody
    @RequestMapping("welcomeTips")
    public CommonResult welcomeTips() throws Exception {
        CommonResult commonResult = new CommonResult();
        BusinessInfoExample businessInfoExample = new BusinessInfoExample();
        businessInfoExample.createCriteria().andManagerIdEqualTo(getLoginAccount().getStaffInfo().getId()).andManagerIsAssessEqualTo(ShortData.s0).andBusinessWorkFlowEqualTo(ShortData.s3);
        int count = businessInfoServices.countByExample(businessInfoExample);

        if (count == 0) {
            return commonResult.setError();
        } else {
            Map map = new HashMap();
            map.put("info", count + "份经办人评价未填写");
            map.put("url", "business/managerAssess/index?managerIsAssess=0");
            commonResult.setData(map);
            return commonResult.setSuccess();
        }
    }



    @RequestMapping("pdf/{businessId}")
    public ResponseEntity<byte[]> pdf(HttpServletRequest request, @PathVariable("businessId") String businessId) throws Exception {


        ManagerAssessExample managerAssessExample = new ManagerAssessExample();
        managerAssessExample.setOrderByClause("ACCESS_TYPE_NUM");
        managerAssessExample.createCriteria().andBusinessIdEqualTo(businessId);
        List<ManagerAssess> managerAssessList = managerAssessServices.selectByExample(managerAssessExample);

        File file = FileUtils.getFile(FileUtils.getTempDirectory(), IDFactory.getSnowflakeId());
        ManagerAssessPdf.createPdf(FileUtils.openOutputStream(file), managerAssessList);
        byte[] bytes = FileUtils.readFileToByteArray(file);
        file.delete();


        HttpHeaders headers = new HttpHeaders();
        headers.setContentDispositionFormData("attachment", UploadDownloadFileUtil.encodeChineseDownloadFileName("经办人评价.pdf", request));
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        return new ResponseEntity<byte[]>(bytes, headers, HttpStatus.OK);

    }

    @RequestMapping("doc/{businessId}")
    public ResponseEntity<byte[]> doc(HttpServletRequest request, @PathVariable("businessId") String businessId) throws Exception {


        ManagerAssessExample managerAssessExample = new ManagerAssessExample();
        managerAssessExample.setOrderByClause("ACCESS_TYPE_NUM");
        managerAssessExample.createCriteria().andBusinessIdEqualTo(businessId);
        List<ManagerAssess> managerAssessList = managerAssessServices.selectByExample(managerAssessExample);

        File file = FileUtils.getFile(FileUtils.getTempDirectory(), IDFactory.getSnowflakeId());
        ManagerAssessDoc.createDoc(FileUtils.openOutputStream(file), managerAssessList);
        byte[] bytes = FileUtils.readFileToByteArray(file);
        file.delete();


        HttpHeaders headers = new HttpHeaders();
        headers.setContentDispositionFormData("attachment", UploadDownloadFileUtil.encodeChineseDownloadFileName("经办人评价.doc", request));
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        return new ResponseEntity<byte[]>(bytes, headers, HttpStatus.OK);

    }







}
